package com.xzj.spring.process;

import com.xzj.spring.annotation.Component;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

/**
 * @ProjectName: SpringDemo
 * @Package: com.xzj.spring.process
 * @ClassName: XZJBeanPostProcessor
 * @Author: xzj
 * @Description:
 * @Date: 2022/7/12 9:32
 * @Version: 1.0
 */
@Component
public class XZJBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws RuntimeException {
        System.out.println(String.format("BeanName:%s, Bean:%s, postProcessBeforeInitialization1", beanName, bean));
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws RuntimeException {
        //是否需要动态代理
        if (beanName.equals("123")) {
            System.out.println("===");
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(bean.getClass());
            enhancer.setCallback((MethodInterceptor) (obj, method, args, methodProxy) -> {
                Object result = null;
                System.out.println("方法调用前");
                result = methodProxy.invokeSuper(obj, args);
                System.out.println(method.getName() + "被调用");
                System.out.println("方法调用后");
                return result;
            });
            Object o = enhancer.create();
            return o;
//            return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{IServer.class},(proxy, method, args)->{
//                System.out.println("保存日志被代理");
//                return method.invoke(bean,args);
//            });
        }
        return bean;
    }
}
